/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.itip.event.send;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.sinodata.bsm.itip.event.TivoliEvent;

/**
 * <p>
 * Description: 采集omnibus中的事件
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-8-13 上午10:16:29          wangyazhou        1.0         To create
 * </p>
 *
 * @since     
 * @see       
 */
public class TransfEventJob implements Job {

    private static final Logger logger = Logger.getLogger("event");

    static final String EVENT = "EVENT";

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {
        try {
            logger.info("[TIP]\t Collect Omnibus Events...");
            sendEventObject(getEventData());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送事件对象   
     * @param list
     */
    private void sendEventObject(List<TivoliEvent> events) {
        /**
         * 如果summary中包含tcp.node中的任意一项，则用此项替换event.node的值
         */
        String nodes = EnvUtil.getInstance().getTpcnodes();
        if (nodes != null && nodes.length() > 0) {
            String[] nodeAry = nodes.split("[,]");
            if (nodeAry != null && nodeAry.length > 0) {
                for (TivoliEvent event : events) {
                    for (int i = 0; i < nodeAry.length; i++) {
                        if (event.getSummary() != null && event.getSummary().contains(nodeAry[i])) {
                            event.setNode(nodeAry[i]);
                            break;
                        }
                    }
                    continue;
                }
            }
        }

        if (events != null && events.size() < 1) {
            return;
        }
        AlertSender.getInstance().send(events, EnvUtil.getInstance().getIp(), EnvUtil.getInstance().getPort());
    }

    /**
     * 查询omnibus数据库  获取事件列表
     * @return
     */
    private List<TivoliEvent> getEventData() {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<TivoliEvent> tivoliEvents = new ArrayList<TivoliEvent>();
        try {
            conn = EnvUtil.getInstance().getConnection();

            String sql = EnvUtil.getInstance().buildSql();

            logger.info(sql);
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            if (rs == null) {
                return null;
            }

            //三个项目  同一张表居然有三种字段名   汉办法 只能把要取的字段写在配置文件里面
            String columns = EnvUtil.getInstance().getColumns();
            String[] colAry = columns.split("[,]");
            if (colAry.length != 6) {
                return null;
            }

            while (rs.next()) {

                TivoliEvent event = new TivoliEvent();
                String time = rs.getString(colAry[0].trim());

                String timestamp = rs.getString(colAry[1].trim());

                event.setItmTime(time == null ? (timestamp == null ? new Date().toString() : timestamp) : time);

                String resourceUnique = rs.getString(colAry[2].trim());
                event.setNode(resourceUnique);

                //                String kpiUnique = rs.getString("ITMSitFullName");
                //                
                //                if (kpiUnique == null || kpiUnique.equals("")) {
                //                    kpiUnique = rs.getString("AlertKey");
                //                }
                //                
                //                event.setTypeCode(kpiUnique);
                String summary = rs.getString(colAry[3].trim());
                event.setSummary(summary);

                String severity = rs.getString(colAry[4].trim());
                event.setSeverity(severity);

                String serial = rs.getString(colAry[5].trim());
                event.setSerial(serial);

                logger.info("[RUDE]\t" + event.toString());
                tivoliEvents.add(event);
            }

            logger.info("[TIP]\t Size Of Event=" + tivoliEvents.size());

            //更新字段
            rs.close();
            ps.close();
            ps = conn.prepareStatement("update alerts.status set CorrScore=1 where CorrScore=0");
            ps.execute();

        } catch (Exception e) {
            logger.error(e);
            EnvUtil.getInstance().closeConn();
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return tivoliEvents;
    }

}
